#include "loginpage.h"
#include "ui_loginpage.h"
#include <main.h>
extern QSettings settings;
LoginPage::LoginPage(QWidget *parent) :
    QMainWindow (parent),
    ui(new Ui::LoginPage)
{

    ui->setupUi(this);

    //    // 保存一个整数数组到 INI 文件
//    QSettings settings("CWNU_SE_2021_CYS", "LoginList");

//    for(int i = 0 ; i < username.size();++i){
//        // 保存一个字符串列表到 INI 文件
//        settings.setValue("LoginList/usernamelist", username[i]);
//        settings.setValue("LoginList/password", password[i]);
//    }
//=================username password ===========================


//    QSettings setting (":/home/LoginList.ini", QSettings::IniFormat);
//       QString value = settings.value("section1/key1", "default_value").toString();
//    QString value = setting.value("username/user1", "default value").toString();

//    qDebug() << value;

    settings.beginGroup("server");
    QString username = settings.value("username", "defaultUsername").toString();
    QString password = settings.value("password", "defaultPassword").toString();
    int state = settings.value("state", 0).toInt();
    usernames.append(username);
    passwords.append(password);
    states.append(state);
    qDebug()<<username<<password<<state;
    settings.endGroup();

    settings.beginGroup("client");
    username = settings.value("username", "defaultUsername").toString();
    password = settings.value("password", "defaultPassword").toString();
    state = settings.value("state", 0).toInt();
    usernames.append(username);
    passwords.append(password);
    states.append(state);
    qDebug()<<username<<password<<state;
    settings.endGroup();
    // 创建 QSettings 对象并设置 INI 文件路径
//        QSettings setting2(":/home/LoginList.ini", QSettings::IniFormat);

//        // 读取 INI 文件中指定节和键的值
//        QString value1 = setting2.value("section1/key1", "defaultValue1").toString();
//        int value2 = setting2.value("section1/key2", 0).toInt();

//        QString value3 = setting2.value("section2/key1", "defaultValue2").toString();
//        bool value4 = setting2.value("section2/key2", false).toBool();

//        // 打印读取到的值
//        qDebug() << "value1: " << value1;
//        qDebug() << "value2: " << value2;
//        qDebug() << "value3: " << value3;
//        qDebug() << "value4: " << value4;
//    QStringList users = settings.value("username/user1").toStringList();QString value = settings.value("username", "default value").toString();
//    QStringList passwords = setting.value("password").toStringList();
//    qDebug() << value<<passwords;
//=========================debug settings=========================
//    if(setting.contains("username/user1"))
//    {

//        qDebug() << "username/user1 = " << value;
//    }
//    else
//    {
//        qDebug() << "username/user1 not found in inifile.ini";
//    }
//    QString value = settings.value("username", "default value").toString();
//    QStringList keys = settings.allKeys();

//    foreach(QString key, keys)
//    {
//      QString value = settings.value(key).toString();
//      qDebug() << key << "=" << value;
//    }
    // 开始读取数组
//    settings.beginGroup("username");

//    int size = settings.value("size").toInt();
////    int size = settings.beginReadArray("username");
//    settings.beginReadArray("values");
//    for (int i = 0; i < size; ++i) {
//        settings.setArrayIndex(i);
//        QString value = settings.value("username").toString();
//        qDebug() << "Array element" << i << "has value:" << value;
////        values.append(value);
//    }
//    settings.endArray();

//    settings.endGroup();

//    int size = settings.beginReadArray("username");
//    for (int i = 0; i < size; ++i) {
//        settings.setArrayIndex(i);
//        QString value = settings.value("username").toString();
//        // 将读取的数组元素输出到控制台
//        username.append(value);
//        qDebug() << "Array element" << i << "has value:" << value;
//    }
//    // 结束读取数组
//    settings.endArray();

//    for (int i = 0; i < size; ++i) {
//        settings.setArrayIndex(i);
//        QString value = settings.value("password").toString();
//        // 将读取的数组元素输出到控制台
//        password.append(value);
//        qDebug() << "Array element" << i << "has value:" << value;
//    }
//    for (int i = 0; i < size; ++i) {
//        settings.setArrayIndex(i);
//        QString value = settings.value("value").toString();
//        // 将读取的数组元素输出到控制台
//        value.append(value);
//        qDebug() << "Array element" << i << "has value:" << value;
//    }
//    // 结束读取数组
//    settings.endArray();
//    QStringList usernameList;
//=======================================================
//    usernameList<<"user1"<<"user2"<<"user3";

//    //写入数组数据
//    settings.beginWriteArray("Username");
//    for(int i=0; i<usernameList.count(); ++i)
//    {
//        settings.setArrayIndex(i);
//        settings.setValue("name",usernameList.at(i));
//    }
//    settings.endArray();

//    //读取数组数据
//    QStringList result;
//    int size = settings.beginReadArray("Username");
//    for(int i=0; i<size; ++i)
//    {
//        settings.setArrayIndex(i);
//        QString name = settings.value("name").toString();
//        result<<name;
//    }
//        settings.endArray();
////===============UI 美化==================================
///



        setWindowFlag(Qt::FramelessWindowHint);

//    setAttribute(Qt::WA_TranslucentBackground);
//    setWindowOpacity(0.99);


////===============UI 美化=================
//    QRect screenRect = QApplication::desktop()->screenGeometry();  // 获取屏幕尺寸
//    int width = screenRect.width();  // 获取屏幕宽度
//    int height = screenRect.height();  // 获取屏幕高度
//    setFixedSize(width * 0.8, height * 0.8); // 设置窗口尺寸为屏幕的
//    setWindowFlags(Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint);
//    setAttribute(Qt::WA_TranslucentBackground);
//    setGeometry(0, 0, width(), height());

//    setMask(create_mask(rect(), 10));


/////setAttribute(Qt::WA_TranslucentBackground, true);
////     Set the background role to QPalette::Window
////     创建QLabel对象
//    QLabel *label = new QLabel(this);

////    设置QLabel对象的背景图片
//    label->setPixmap(QPixmap("://home/image/bg.jpg"));

////     放置QLabel对象到主窗口中
//    label->setGeometry(0, 0, this->width(), this->height());
//    label->show();

//     创建QGraphicsBlurEffect对象
//    QGraphicsBlurEffect *blurEffect = new QGraphicsBlurEffect(this);
//    blurEffect->setBlurRadius(5); // 设置磨砂半径
//    label->setScaledContents(true); // 设置ScaledContents属性
//     将QGraphicsBlurEffect对象应用于QLabel对象
//    label->setGraphicsEffect(blurEffect);
//============================================================
//    QVBoxLayout *layout = new QVBoxLayout(this);

//    // Create a QLabel to display the background
//    QLabel *background = new QLabel(this);
//    background->setPixmap(QPixmap(":/background.png"));
//    background->setScaledContents(true);

//    // Create a QGraphicsOpacityEffect for the background
//    m_opacityEffect = new QGraphicsOpacityEffect(this);
//    m_opacityEffect->setOpacity(0.7);
//    background->setGraphicsEffect(m_opacityEffect);

//    layout->addWidget(background);
///// // 创建QLabel控件并设置背景图片
//    QLabel *backgroundLabel = new QLabel(this);
//    backgroundLabel->setPixmap(QPixmap(":/path/to/background/image.png"));
//    // 设置QLabel控件的位置和大小
//    backgroundLabel->setGeometry(0, 0, width(), height());
//    // 设置窗口或控件的布局方式为绝对坐标
//    setLayout(nullptr);

//    // 强制背景透明
//    setAttribute(Qt::WA_TranslucentBackground, true);
//    // Set the background role to QPalette::Window
//    setBackgroundRole(QPalette::Window);
//    // 从文件加载图片
//    QPixmap bkgnd("://home/image/bg.jpg");


//    // 创建一个QLabel控件，并设置它的背景图片为bkgnd
//    QLabel *background = new QLabel(this);
//    background->setPixmap(bkgnd);
//    background->setGeometry(0, 0, bkgnd.width(), bkgnd.height());

//    // 获取QLoginPage的centralWidget控件
//    QWidget *centralWidget = QLoginPage::centralWidget();

//    // 改变centralWidget的背景模式
//    centralWidget->setAutoFillBackground(true);
//    centralWidget->setPalette(QPalette(Qt::white));

//    // 将刚才的QLabel控件插入到centralWidget的布局中
//    QVBoxLayout *layout = new QVBoxLayout(centralWidget);
//    layout->addWidget(background);
//    unmanedsupermarketsys umsmsys;
//    sysclient sysClient;
//    qint32 state = on_loginbtn_clicked();
//    switch (state) {
//    case 0: umsmsys.show();break;
//    case 1: sysClient.show();break;
//    default:;break;
//    }
//    unmanedsupermarketsys umsmsys;
//    sysclient sysClient;
//    if(state == 0){//页面间跳转
//        umsmsys.show();
//    }else if(state == 1){
//        sysClient.show();
//    }
    // 将参数保存
//    parameter = state;
//    QMessageBox::information(this,
//            tr("用户名及密码"),
//         tr("server 1 (服务端)\n"
//            "client 0505 (客户端)\n ")
//               );
}

LoginPage::~LoginPage()
{
    delete ui;
}


void LoginPage::on_loginbtn_clicked()
{



//    int myArray[3] = { 1, 2, 3 };
//    QByteArray byteArray(reinterpret_cast<const char*>(myArray), sizeof(myArray));
//    settings.setValue("MySection/myArray", byteArray);



    //===================================
    QString id = ui->usernameline->text();// 存用户名变量
    QString secret = ui->passwordline->text();// 存密码变量

    state = -1;
//    qDebug()<< id <<secret;


    for(qint32 i = 0 ; i < 2 ; ++i){
//        qDebug()<< username[i] <<password[i];
        if( id !=usernames[i]){
            continue;
        }
        if( secret == passwords[i]){
            state = i;
        }
    }
    if(id.isEmpty()||secret.isEmpty()){
        state = 2;
    }
//    QPushButton *btn = ui->loginbtn;
    unmanedsupermarketsys * umsmsys = new unmanedsupermarketsys;
    sysclient *sysClient = new sysclient;
//    emit parameterOutput(parameter);
//    close();

    switch (state) {
        case 0:
//            connect(btn,SIGNAL(clicked()),this,SLOT(accept()));
//            qDebug()<<"无人超市水果采集系统（服务端）";
//            this->exec();
        QMessageBox::information(this,
                tr("登录成功"),
             tr("正在进入服务端...\n")
                );

                close();
                umsmsys->show();
//                close();
            break;
        case 1:
//            connect(btn,SIGNAL(clicked()),this,SLOT(reject()));
//            qDebug()<<"无人超市水果采集系统（客户端）";
//            this->exec();
                QMessageBox::information(this,
                tr("登录成功"),
                tr("正在进入客户端...\n")
                );

                close();
                sysClient->show();

            break;

        case 2:
            QMessageBox::information(this,
            tr("请输入信息"),
            tr("请输入信息...\n")
            );
            break;
        default:
            //TODO
            QMessageBox::critical(this,
            tr("登录失败"),
            tr("用户名或密码错误\n")
            );

            break;
        }
//    emit sendData(state);
}


void LoginPage::on_checkBox_clicked()
{
    if(ui->checkBox->isChecked()){
        ui->passwordline->setEchoMode(QLineEdit::Password);
        ui->checkBox->setText("密码隐藏");
    }else {
        ui->passwordline->setEchoMode(QLineEdit::Normal);
        ui->checkBox->setText("密码隐藏");
    }
}
void LoginPage::mousePressEvent(QMouseEvent *event)
{
    m_dragging = true;
    m_lastPos = event->globalPos() - frameGeometry().topLeft();
}

void LoginPage::mouseMoveEvent(QMouseEvent *event)
{
    if (m_dragging)
    {
        QPoint newPos = event->globalPos() - m_lastPos;
        move(newPos);
    }
}

void LoginPage::mouseReleaseEvent(QMouseEvent *event)
{
    Q_UNUSED(event)
    m_dragging = false;
}


